#include "SKFunctionSet.h"
#include "ui_SKFunctionSet.h"
#include "ScanCameraDevice.h"
#include <QDebug>
#include <QMouseEvent>
#include <QMessageBox>

SKFunctionSet::SKFunctionSet(ScanCameraDevice * device,QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SKFunctionSet),
    m_device(device),
    m_IsMonitor(false),
    m_dragging(false),
    m_mousePressed(false),
    m_lastMousePosition(QPoint())
{
    ui->setupUi(this);
    // 设置窗口为无边框
    this->setWindowFlags(Qt::FramelessWindowHint| Qt::Dialog);

    // 初始化按钮组
    initializeButtonGroups();
    
    // 如果提供了设备指针，建立与设备的连接
    if (m_device) {
        fetchParametersFromDevice();
        connectToDevice();
    } else {
        // 设置默认值
        resetUI();
    }

    m_MonitorTimer.setInterval(5100);
    connect(&m_MonitorTimer,&QTimer::timeout,this,[this](){
        //异步监控查询
        QtConcurrent::run([this](){
            m_device->setMonitorSignalQuery();
        });
        //更新监控信息
        onUpdateMonitorInfo();
    });
}

SKFunctionSet::~SKFunctionSet()
{
    delete ui;
}

/**
 * @brief 获取当前设备指针
 * @return Device* 设备指针
 */
ScanCameraDevice *SKFunctionSet::getDevice() const
{
    return m_device;
}

void SKFunctionSet::connectToDevice()
{
    if (!m_device) return;
    
    // 断开现有连接
    disconnectFromDevice();
    
    // 连接信号槽
    connect(ui->swt_shutterControl_enable, &SwitchSliderWidget::toggled, this, &SKFunctionSet::onShutterControlChanged);

    connect(m_workModeButtonGroup, QOverload<QAbstractButton*, bool>::of(&QButtonGroup::buttonToggled), this, &SKFunctionSet::onWorkModeChanged);
    connect(m_scanSpeedModeButtonGroup, QOverload<QAbstractButton*, bool>::of(&QButtonGroup::buttonToggled), this, &SKFunctionSet::onComponentSelectionChanged);
    connect(m_triggerSourceButtonGroup, QOverload<QAbstractButton*, bool>::of(&QButtonGroup::buttonToggled), this, &SKFunctionSet::onTriggerSourceChanged);

    connect(ui->btn_gain_set, &QPushButton::clicked, this, &SKFunctionSet::onGainSetClicked);
    connect(ui->btn_gain_cancel, &QPushButton::clicked, this, &SKFunctionSet::onGainCancelClicked);

    //mcp
    connect(ui->chk_gateMode_mcp, &SwitchSliderWidget::toggled, this, &SKFunctionSet::onCathodeGatingModeToggled);
    //外触发
    connect(ui->chk_gateMode_external, &SwitchSliderWidget::toggled, this, &SKFunctionSet::onExternalGatingModeToggled);

    //阴极门控
    connect(ui->chk_gate_cathode, &SwitchSliderWidget::toggled, this, &SKFunctionSet::onCathodeGatingToggled);
    //外触发
    connect(ui->chk_gate_external, &SwitchSliderWidget::toggled, this, &SKFunctionSet::onExternalGatingToggled);
    
    // 启动监控
    connect(ui->chk_monitor_enable, &SwitchSliderWidget::toggled, this, &SKFunctionSet::onMonitorEnabledChanged);

    connect(m_device,&ScanCameraDevice::adValueChanged,this,[this](const QVector<uint16_t>& adValues){
        // 获取AD值并更新表格
        for(int i = 0; i < adValues.size() && i < 8; ++i)
        {
            // 将AD值转换为电压值
            double voltage = adValues[i] / 1000.0;
            QTableWidgetItem *item = new QTableWidgetItem(QString("%1").arg(voltage, 0, 'f', 3));
            item->setTextAlignment(Qt::AlignCenter);
            ui->tableWidget->setItem(i, 0, item);
        }
    });
    connect(m_device,&ScanCameraDevice::gpioStatusChanged,this,[this](const QVector<bool>& gpioStatus){
        // 获取GPIO状态并更新表格
        for(int i = 0; i < gpioStatus.size() && i < 8; ++i)
        {
            QString status = gpioStatus[i] ? "高" : "低";
            QTableWidgetItem *item = new QTableWidgetItem(status);
            item->setTextAlignment(Qt::AlignCenter);
            ui->tableWidget->setItem(i, 1, item);
        }
    });
    
    // 阴极门控设置
    connect(ui->btn_cathode_set, &QPushButton::clicked, this, &SKFunctionSet::onCathodeGateSetClicked);
    connect(ui->btn_cathode_cancel, &QPushButton::clicked, this, &SKFunctionSet::onCathodeGateCancelClicked);
    
    // MCP门控设置
    connect(ui->btn_mcp_set, &QPushButton::clicked, this, &SKFunctionSet::onMCPGateSetClicked);
    connect(ui->btn_mcp_cancel, &QPushButton::clicked, this, &SKFunctionSet::onMCPGateCancelClicked);
    
    // 触发延迟设置
    connect(ui->btn_triggerDelay_set, &QPushButton::clicked, this, &SKFunctionSet::onTriggerDelaySetClicked);
    connect(ui->btn_triggerDelay_cancel, &QPushButton::clicked, this, &SKFunctionSet::onTriggerDelayCancelClicked);
    
    // 关闭按钮
    connect(ui->tbtn_close, &QToolButton::clicked, this, &SKFunctionSet::onCloseButtonClicked);
       
}

void SKFunctionSet::disconnectFromDevice()
{
    // 断开所有信号槽连接
    disconnect(ui->swt_shutterControl_enable, nullptr, this, nullptr);
    disconnect(m_workModeButtonGroup, nullptr, this, nullptr);
    disconnect(m_scanSpeedModeButtonGroup, nullptr, this, nullptr);
    disconnect(m_triggerSourceButtonGroup, nullptr, this, nullptr);

    disconnect(ui->btn_gain_set, nullptr, this, nullptr);
    disconnect(ui->btn_gain_cancel, nullptr, this, nullptr);
    
    // 断开监控和门控相关控件的连接
    disconnect(ui->btn_cathode_set, nullptr, this, nullptr);
    disconnect(ui->btn_cathode_cancel, nullptr, this, nullptr);
    disconnect(ui->btn_mcp_set, nullptr, this, nullptr);
    disconnect(ui->btn_mcp_cancel, nullptr, this, nullptr);
    
    // 断开触发延迟设置按钮连接
    disconnect(ui->btn_triggerDelay_set, nullptr, this, nullptr);
    disconnect(ui->btn_triggerDelay_cancel, nullptr, this, nullptr);
    
    // 断开关闭按钮连接
    disconnect(ui->tbtn_close, nullptr, this, nullptr);
    
    // 断开设备连接
    if (m_device)
    {
        disconnect(this, nullptr, m_device, nullptr);
        disconnect(m_device, nullptr, this, nullptr);
    }
    
    qDebug() << "Disconnected from device in SKFunctionSet";
}

void SKFunctionSet::initializeButtonGroups()
{
    // 工作模式按钮组
    m_workModeButtonGroup = new QButtonGroup(this);
    m_workModeButtonGroup->addButton(ui->rdo_workMode_scan);
    m_workModeButtonGroup->addButton(ui->rdo_workMode_focus);
    
    // 扫描速度模式按钮组
    m_scanSpeedModeButtonGroup = new QButtonGroup(this);
    m_scanSpeedModeButtonGroup->addButton(ui->rdo_scanSpeed_fast);
    m_scanSpeedModeButtonGroup->addButton(ui->rdo_scanSpeed_medium);
    m_scanSpeedModeButtonGroup->addButton(ui->rdo_scanSpeed_slow);
    
    // 触发源按钮组
    m_triggerSourceButtonGroup = new QButtonGroup(this);
    m_triggerSourceButtonGroup->addButton(ui->rdo_triggerSource_scanLine);
    m_triggerSourceButtonGroup->addButton(ui->rdo_triggerSource_gateLine);

    // 根据触发源更新门控模式分组框的启用状态
    ui->grp_gateMode->setEnabled(false);
    ui->grp_triggerDelay_setting->setEnabled(true);
}

void SKFunctionSet::resetUI()
{
    // 重置UI控件状态
    ui->rdo_workMode_scan->setChecked(true);
    ui->sld_gain_gain1->setValue(0);
    ui->sld_gain_gain2->setValue(0);
    ui->spinBox_Gain1->setValue(0);
    ui->spinBox_Gain2->setValue(0);

    ui->rdo_scanSpeed_fast->setChecked(true);
    ui->swt_shutterControl_enable->setChecked(false);
    ui->rdo_triggerSource_scanLine->setChecked(true);
    
    // 启动监控默认值
    ui->chk_monitor_enable->setChecked(false);
    
    // 门控模式相关控件默认值
    ui->chk_gateMode_mcp->setChecked(false);
    ui->chk_gateMode_external->setChecked(false);
    ui->sb_gateMode_delay_ms->setValue(0);
    ui->sb_gateMode_delay_us->setValue(0);
    ui->sb_gateMode_delay_ns->setValue(0);
    ui->sb_gateMode_pulseWidth_ms->setValue(0);
    ui->sb_gateMode_pulseWidth_us->setValue(0);
    ui->sb_gateMode_pulseWidth_ns->setValue(0);
    
    // 阴极门控相关控件默认值
    ui->sb_gate_delay_ms->setValue(0);
    ui->sb_gate_delay_us->setValue(0);
    ui->sb_gate_delay_ns->setValue(0);
    ui->sb_gate_pulseWidth_ms->setValue(0);
    ui->sb_gate_pulseWidth_us->setValue(0);
    ui->sb_gate_pulseWidth_ns->setValue(0);
    ui->chk_gate_cathode->setChecked(false);
    ui->chk_gate_external->setChecked(false);
    
}


void SKFunctionSet::fetchParametersFromDevice()
{
    // 快门控制状态
    setShutterControl(m_device->getParameter("ShutterOpen").toBool());
    
    // 工作模式
    setWorkMode(m_device->getParameter("WorkMode").toInt());

    // 扫描档位设置
    setComponentSelection(m_device->getParameter("ComponentSelection").toInt());
    //TODO 档位值设置

    // 触发源设置
    setTriggerSource(m_device->getParameter("TriggerSource").toInt());
    
    // 增益值设置
    setGain1(m_device->getParameter("MCPGain1").toInt());
    setGain2(m_device->getParameter("MCPGain2").toInt());
    
    // 启动监控
    setMonitorEnabled(m_device->getParameter("MonitorEnabled").toBool());
    //TODO监控数据

    // 门控设置

    // 阴极门控模式参数
    setCathodeGatingMode(m_device->getParameter("CathodeGatingMode").toUInt());
    setCathodeGatingTriggerDelay(m_device->getParameter("CathodeGatingDelayNs").toInt());
    setCathodeGatingPulseWidth(m_device->getParameter("CathodeGatingPulseWidthNs").toInt());

    // MCP门控模式参数
    setMCPGateMode(m_device->getParameter("MCPGatingMode").toUInt());
    setMCPDelay(m_device->getParameter("MCPGatingDelayNs").toInt());
    setMCPPulseWidth(m_device->getParameter("MCPGatingPulseWidthNs").toInt());
}

int SKFunctionSet::getWorkMode()
{
    // 从UI控件获取工作模式，不直接从设备获取
    if (ui->rdo_workMode_scan->isChecked()) {
        return 0; // 扫描模式
    } else if (ui->rdo_workMode_focus->isChecked()) {
        return 1; // 聚焦模式
    }
    return 0; // 默认返回扫描模式
}

void SKFunctionSet::setWorkMode(int mode)
{ 
    disconnect(m_workModeButtonGroup, QOverload<QAbstractButton*, bool>::of(&QButtonGroup::buttonToggled), this, &SKFunctionSet::onWorkModeChanged);
    if (mode == 0)
    {
        ui->rdo_workMode_scan->setChecked(true);
    }
    else if (mode == 1)
    {
        ui->rdo_workMode_focus->setChecked(true);
    }
    connect(m_workModeButtonGroup, QOverload<QAbstractButton*, bool>::of(&QButtonGroup::buttonToggled), this, &SKFunctionSet::onWorkModeChanged);
}

int SKFunctionSet::getComponentSelection()
{
    // 从UI控件获取扫描速度模式，不直接从设备获取
    if (ui->rdo_scanSpeed_fast->isChecked())
    {
        ui->cbx_scanSpeed_fast->setEnabled(true);
        ui->cbx_scanSpeed_medium->setEnabled(false);
        ui->cbx_scanSpeed_slow->setEnabled(false);
        return 1; // 快速
    } else if (ui->rdo_scanSpeed_medium->isChecked())
    {
        ui->cbx_scanSpeed_fast->setEnabled(false);
        ui->cbx_scanSpeed_medium->setEnabled(true);
        ui->cbx_scanSpeed_slow->setEnabled(false);
        return 2; // 中速
    } else if (ui->rdo_scanSpeed_slow->isChecked())
    {
        ui->cbx_scanSpeed_fast->setEnabled(false);
        ui->cbx_scanSpeed_medium->setEnabled(false);
        ui->cbx_scanSpeed_slow->setEnabled(true);
        return 3; // 慢速
    }
    ui->cbx_scanSpeed_fast->setEnabled(true);
    ui->cbx_scanSpeed_medium->setEnabled(false);
    ui->cbx_scanSpeed_slow->setEnabled(false);
    return 1; // 默认返回快速
}

void SKFunctionSet::setComponentSelection(int mode)
{
    disconnect(m_scanSpeedModeButtonGroup, QOverload<QAbstractButton*, bool>::of(&QButtonGroup::buttonToggled), this, &SKFunctionSet::onComponentSelectionChanged);
    switch (mode)
    {
        case 1:
            ui->rdo_scanSpeed_fast->setChecked(true);
            break;
        case 2:
            ui->rdo_scanSpeed_medium->setChecked(true);
            break;
        case 3:
            ui->rdo_scanSpeed_slow->setChecked(true);
            break;
        default:
            break;
    }
    
    // 更新下拉框状态
    ui->cbx_scanSpeed_fast->setEnabled(mode == 1);
    ui->cbx_scanSpeed_medium->setEnabled(mode == 2);
    ui->cbx_scanSpeed_slow->setEnabled(mode == 3);
    connect(m_scanSpeedModeButtonGroup, QOverload<QAbstractButton*, bool>::of(&QButtonGroup::buttonToggled), this, &SKFunctionSet::onComponentSelectionChanged);
}

int SKFunctionSet::getGain1()
{
    return ui->sld_gain_gain1->value();
}

void SKFunctionSet::setGain1(int gain)
{
    ui->sld_gain_gain1->setValue(gain);
    ui->spinBox_Gain1->setValue(gain);
}

int SKFunctionSet::getGain2()
{
    return ui->sld_gain_gain2->value();
}

void SKFunctionSet::setGain2(int gain)
{
    ui->sld_gain_gain2->setValue(gain);
    ui->spinBox_Gain2->setValue(gain);
}

bool SKFunctionSet::getShutterControl()
{
    return ui->swt_shutterControl_enable->isChecked();
}

void SKFunctionSet::setShutterControl(bool enable)
{
    disconnect(ui->swt_shutterControl_enable, &SwitchSliderWidget::toggled, this, &SKFunctionSet::onShutterControlChanged);

    ui->swt_shutterControl_enable->setChecked(enable);

    connect(ui->swt_shutterControl_enable, &SwitchSliderWidget::toggled, this, &SKFunctionSet::onShutterControlChanged);

}

int SKFunctionSet::getTriggerSource()
{
    // 从UI控件获取触发源，不直接从设备获取
    if (ui->rdo_triggerSource_scanLine->isChecked())
    {
        return 0; // 扫描线触发
    }
    else if (ui->rdo_triggerSource_gateLine->isChecked())
    {
        return 1; // 门控线控制
    }
    return 0; // 默认返回扫描线触发
}

void SKFunctionSet::setTriggerSource(int source)
{

    if (source == 0)
    {
        ui->rdo_triggerSource_scanLine->setChecked(true);
    }
    else if (source == 1)
    {
        ui->rdo_triggerSource_gateLine->setChecked(true);
    }

    // 根据触发源更新门控模式分组框的启用状态
    ui->grp_gateMode->setEnabled(source == 1);
    ui->grp_triggerDelay_setting->setEnabled(source == 0);
}

// 启动监控相关方法
bool SKFunctionSet::getMonitorEnabled() const
{
    return ui->chk_monitor_enable->isChecked();
}

void SKFunctionSet::setMonitorEnabled(bool enabled)
{
    ui->chk_monitor_enable->setChecked(enabled);
}

// 门控设置相关方法
uint8_t SKFunctionSet::getCathodeGatingMode() const
{
    uint8_t mode = ui->chk_gate_cathode->isChecked() ? 2 : 3;
    if (mode == 2 && ui->chk_gate_external->isChecked())
    {
        mode = 1;
    }
    return mode;
}

void SKFunctionSet::setCathodeGatingMode(uint8_t mode)
{
    //mode（1:门控开+外触发, 2:门控开, 3:门控关）
    // 根据模式设置UI控件
    bool gatingEnabled = mode != 3;
    bool externalTrigger = (mode == 1);

    ui->chk_gate_cathode->setChecked(gatingEnabled);
    ui->chk_gate_external->setChecked(externalTrigger);

    // 更新延迟和脉冲宽度控件的启用状态
//    ui->sb_gate_delay_ms->setEnabled(mode == 2);
//    ui->sb_gate_delay_us->setEnabled(mode == 2);
//    ui->sb_gate_delay_ns->setEnabled(mode == 2);
//    ui->sb_gate_pulseWidth_ms->setEnabled(mode == 2);
//    ui->sb_gate_pulseWidth_us->setEnabled(mode == 2);
//    ui->sb_gate_pulseWidth_ns->setEnabled(mode == 2);

//    ui->chk_gate_external->setEnabled(mode == 1 || mode == 2);
}

int SKFunctionSet::getCathodeGatingTriggerDelay() const
{

    return ui->sb_gate_delay_ms->value()*1000*1000+ui->sb_gate_delay_us->value()*1000+
            ui->sb_gate_delay_ns->value();
}

void SKFunctionSet::setCathodeGatingTriggerDelay(int delay)
{
    ui->sb_gate_delay_ms->setValue(delay/1000/1000);
    ui->sb_gate_delay_us->setValue((delay/1000)%1000);
    ui->sb_gate_delay_ns->setValue(delay%1000);
}

int SKFunctionSet::getCathodeGatingPulseWidth() const
{
    return ui->sb_gate_pulseWidth_ms->value()*1000*1000+ui->sb_gate_pulseWidth_us->value()*1000+
            ui->sb_gate_pulseWidth_ns->value();
}

void SKFunctionSet::setCathodeGatingPulseWidth(int width)
{
    ui->sb_gate_pulseWidth_ms->setValue(width/1000/1000);
    ui->sb_gate_pulseWidth_us->setValue((width/1000)%1000);
    ui->sb_gate_pulseWidth_ns->setValue(width%1000);
}

// MCP门控模式相关方法
bool SKFunctionSet::getMCPGateMode() const
{
    uint8_t mode = ui->chk_gateMode_mcp->isChecked() ? 2 : 3;
    if (mode == 2 && ui->chk_gateMode_external->isChecked())
    {
        mode = 1;
    }
    return mode;
}

void SKFunctionSet::setMCPGateMode(uint8_t mode)
{
    // 根据模式设置UI控件
    bool gatingEnabled = mode != 3;
    bool externalTrigger = (mode == 1);

    ui->chk_gateMode_mcp->setChecked(gatingEnabled);
    ui->chk_gateMode_external->setChecked(externalTrigger);

    // 更新延迟和脉冲宽度控件的启用状态
//    ui->sb_gateMode_delay_ms->setEnabled(mode == 2);
//    ui->sb_gateMode_delay_us->setEnabled(mode == 2);
//    ui->sb_gateMode_delay_ns->setEnabled(mode == 2);
//    ui->sb_gateMode_pulseWidth_ms->setEnabled(mode == 2);
//    ui->sb_gateMode_pulseWidth_us->setEnabled(mode == 2);
//    ui->sb_gateMode_pulseWidth_ns->setEnabled(mode == 2);

//    ui->chk_gateMode_external->setEnabled(mode == 1 || mode == 2);
}

int SKFunctionSet::getMCPDelay() const
{

    return ui->sb_gateMode_delay_ms->value()*1000*1000+ui->sb_gateMode_delay_us->value()*1000+
            ui->sb_gateMode_delay_ns->value();
}

void SKFunctionSet::setMCPDelay(int delay)
{
    ui->sb_gateMode_delay_ms->setValue(delay/1000/1000);
    ui->sb_gateMode_delay_us->setValue((delay/1000)%1000);
    ui->sb_gateMode_delay_ns->setValue(delay%1000);
}

int SKFunctionSet::getMCPPulseWidth() const
{
    return ui->sb_gate_pulseWidth_ms->value()*1000*1000+ui->sb_gate_pulseWidth_us->value()*1000+
            ui->sb_gate_pulseWidth_ns->value();
}

void SKFunctionSet::setMCPPulseWidth(int width)
{
    ui->sb_gateMode_pulseWidth_ms->setValue(width/1000/1000);
    ui->sb_gateMode_pulseWidth_us->setValue((width/1000)%1000);
    ui->sb_gateMode_pulseWidth_ns->setValue(width%1000);
}

int SKFunctionSet::getTriggerDelay()
{
    return ui->spinBox_TriggerDelay_Scan_ms->value()*1000*1000+ui->spinBox_TriggerDelay_Scan_us->value()*1000+
            ui->spinBox_TriggerDelay_Scan_ns->value();
}

void SKFunctionSet::setTriggerDelay(int delay)
{
    ui->spinBox_TriggerDelay_Scan_ms->setValue(delay/1000/1000);
    ui->spinBox_TriggerDelay_Scan_us->setValue((delay/1000)%1000);
    ui->spinBox_TriggerDelay_Scan_ns->setValue(delay%1000);
}

int SKFunctionSet::getTriggerPulseWidth()
{
    return ui->spinBox_TriggerDelay_Output_ms->value()*1000*1000+ui->spinBox_TriggerDelay_Output_us->value()*1000+
            ui->spinBox_TriggerDelay_Output_ns->value();
}

void SKFunctionSet::setTriggerPulseWidth(int width)
{
    ui->spinBox_TriggerDelay_Output_ms->setValue(width/1000/1000);
    ui->spinBox_TriggerDelay_Output_us->setValue((width/1000)%1000);
    ui->spinBox_TriggerDelay_Output_ns->setValue(width%1000);
}

/**
 * @brief SKFunctionSet::updateConfig 当配置更新后更新UI状态
 */
void SKFunctionSet::updateConfig(QVariantMap vmap)
{
    ui->swt_shutterControl_enable->setEnabled(vmap["ShutterEnable"].toBool());
    //gain
    {
        ui->sld_gain_gain1->setEnabled(vmap["Gain1Enable"].toBool());
        ui->spinBox_Gain1->setEnabled(vmap["Gain1Enable"].toBool());

        ui->sld_gain_gain2->setEnabled(vmap["Gain2Enable"].toBool());
        ui->spinBox_Gain2->setEnabled(vmap["Gain2Enable"].toBool());

        ui->btn_gain_set->setEnabled(vmap["Gain1Enable"].toBool() || vmap["Gain2Enable"].toBool());
        ui->btn_gain_cancel->setEnabled(vmap["Gain1Enable"].toBool() || vmap["Gain2Enable"].toBool());
    }
    //mcp
    {
        ui->mcp_controllere_widget->setEnabled(vmap["McpGateEnable"].toBool());
        ui->mcp_controller_edit_widget->setEnabled(vmap["McpGateEnable"].toBool());
        ui->mcp_controller_set_widget->setEnabled(vmap["McpGateEnable"].toBool());
    }
    //gate
    {
        ui->gate_controller_widget->setEnabled(vmap["CathodeControlEnable"].toBool());
        ui->gate_edit_widget->setEnabled(vmap["CathodeControlEnable"].toBool());
        ui->gate_controller_set_widget->setEnabled(vmap["CathodeControlEnable"].toBool());
    }
    //
    {
        //8
        ui->cbx_scanSpeed_fast->clear();
        ui->cbx_scanSpeed_medium->clear();
        ui->cbx_scanSpeed_slow->clear();
        for(int i = 0 ; i < 8 ; i ++){
            ui->cbx_scanSpeed_fast->addItem(vmap[QString("Fast").append(QString::number(i))].toString());
            ui->cbx_scanSpeed_medium->addItem(vmap[QString("Medium").append(QString::number(i))].toString());
            ui->cbx_scanSpeed_slow->addItem(vmap[QString("Slow").append(QString::number(i))].toString());
        }
    }
}

// 槽函数实现
void SKFunctionSet::onWorkModeChanged(QAbstractButton* button, bool checked)
{
    Q_UNUSED(button)
    if (!checked) return;
    
    // 根据选中的按钮确定工作模式
    int mode = getWorkMode();

    if(0==mode)
    {
        int triggerMode=m_device->getParameter("ScanMode").toInt();
        CommandResult result = m_device->setScanMode(triggerMode);
        if (CommandResult::Success == result)
        {
            emit writeLog(QString("工作模式设置成功 - %1").arg("扫描模式"), 0, true);
        }
        else
        {
            emit writeLog(QString("工作模式设置失败 - %1").arg("扫描模式"),2,false);
        }
    }
    else
    {
        CommandResult result = m_device->setFocusMode();
        if (CommandResult::Success == result)
        {
            emit writeLog(QString("工作模式设置成功 - %1").arg("聚焦模式"), 0, true);
        }
        else
        {
            emit writeLog(QString("工作模式设置失败 - %1").arg("聚焦模式"), 2, false);
        }
    }
}

void SKFunctionSet::onShutterControlChanged(bool checked)
{
    CommandResult result = m_device->setShutterControl(checked);
    if (CommandResult::Success == result)
    {
        emit writeLog(QString("快门%1成功").arg(checked ? "开启" : "关闭"), 0, true);
    }
    else
    {
        disconnect(ui->swt_shutterControl_enable, &SwitchSliderWidget::toggled, this, &SKFunctionSet::onShutterControlChanged);
        ui->swt_shutterControl_enable->setEnabled(false);
        connect(ui->swt_shutterControl_enable, &SwitchSliderWidget::toggled, this, &SKFunctionSet::onShutterControlChanged);
        emit writeLog(QString("快门%1失败").arg(checked ? "开启" : "关闭"), 2, false);
    }
    emit syncParameters();
}

void SKFunctionSet::onGainSetClicked()
{
    // 使用getGain1()和getGain2()函数从UI获取当前增益值
    int gain1 = getGain1();
    int gain2 = getGain2();
    
    // 同时设置两个增益值到设备
    if (m_device)
    {
        CommandResult result = m_device->setMCPGain(gain1, gain2);
        if (CommandResult::Success == result)
        {
            setGain1(gain1);
            setGain2(gain2);
            emit writeLog(QString("增益设置成功 - Gain1: %1V, Gain2: %2V").arg(gain1).arg(gain2), 0, true);
        }
        else
        {
            emit writeLog(QString("增益设置失败 - Gain1: %1V, Gain2: %2V").arg(gain1).arg(gain2), 2, false);
        }
    }
    else
    {
        emit writeLog("设备未连接，无法设置增益", 2, false);
    }
    emit syncParameters();
}

void SKFunctionSet::onGainCancelClicked()
{
    setGain1(m_device->getParameter("MCPGain1").toInt());
    setGain2(m_device->getParameter("MCPGain2").toInt());
}

void SKFunctionSet::onComponentSelectionChanged(QAbstractButton* button, bool checked)
{
    Q_UNUSED(button)
    static QString logMsg[] = {"快", "中", "慢"};
    if (!checked) return;
    
    // 根据选中的按钮确定扫描速度模式
    int componentSelection = getComponentSelection();

    // 设置到设备
    uint8_t gearPosition;
    switch(componentSelection)
    {
        case 1:
        {
            gearPosition= m_device->getParameter("FastGearPosition").toUInt();
        }break;
        case 2:
        {
            gearPosition= m_device->getParameter("MiddleGearPosition").toUInt();
        }break;
        case 3:
        {
            gearPosition= m_device->getParameter("SlowGearPosition").toUInt();
        }break;
        default:
            return;
    }
    // 直接调用设备的setScanGear方法
    CommandResult result = m_device->setGearPosition(gearPosition,componentSelection);
    if(CommandResult::Success==result)
    {
        emit writeLog(QString("%1档位设置成功!").arg(logMsg[componentSelection-1]),0,true);
    }
    else
    {
        emit writeLog(QString("%1档位设置失败!").arg(logMsg[componentSelection-1]),2,false);
    }
    emit syncParameters();
}

void SKFunctionSet::onTriggerSourceChanged(QAbstractButton* button, bool checked)
{
    Q_UNUSED(button)
    if (!checked) return;
    
    // 根据选中的按钮确定触发源
    int source = getTriggerSource();
    
    // 设置到设备
    CommandResult result = m_device->setTriggerSource(source);
    if (CommandResult::Success == result)
    {
        emit writeLog(QString("触发源设置成功 - %1").arg(source == 0 ? "扫描线触发" : "门控线触发"), 0, true);
    }
    else
    {
        emit writeLog(QString("触发源设置失败 - %1").arg(source == 0 ? "扫描线触发" : "门控线触发"), 2, false);
    }
    ui->grp_gateMode->setEnabled(source==1);
    ui->grp_triggerDelay_setting->setEnabled(source==0);
}


void SKFunctionSet::onTriggerDelayChanged()
{
    // 处理触发延时变更
    qInfo() << "SKFunctionSet: 触发延时参数已变更";
    // 实际实现中应调用设备的API设置触发延时
}

// 阴极门控设置按钮点击槽函数
void SKFunctionSet::onCathodeGateSetClicked()
{
    int cathodeGatingmode=getCathodeGatingMode();
    int delay_ns = getCathodeGatingTriggerDelay();
    int pulse_ns = getCathodeGatingPulseWidth();
    
    // 设置设备门控参数
    CommandResult result = m_device->setCathodeGating(cathodeGatingmode, delay_ns,pulse_ns);
    if (CommandResult::Success == result)
    {
        emit writeLog("阴极门控参数设置成功", 0, true);
    }
    else
    {
        emit writeLog("阴极门控参数设置失败", 2, false);
    }
    ui->gate_edit_widget->setEnabled(ui->chk_gate_cathode->isChecked() && !ui->chk_gate_external->isChecked());
    emit syncParameters();
}

// 阴极门控取消按钮点击槽函数
void SKFunctionSet::onCathodeGateCancelClicked()
{
    // 重新从设备获取参数更新UI
    setCathodeGatingMode(m_device->getParameter("CathodeGatingMode").value<uint8_t>());
    setCathodeGatingTriggerDelay(m_device->getParameter("CathodeGatingDelayNs").value<int>());
    setCathodeGatingPulseWidth(m_device->getParameter("CathodeGatingPulseWidthNs").value<int>());
}

// MCP门控模式变更槽函数
void SKFunctionSet::onMCPGateSetClicked()
{
    // 设置设备MCP门控模式
    int MCPGatingmode=getMCPGateMode();
    int delay_ns = getMCPDelay();
    int pulse_ns = getMCPPulseWidth();

    // 设置设备门控参数
    CommandResult result = m_device->setMCPGating(MCPGatingmode, delay_ns,pulse_ns);
    if (CommandResult::Success == result)
    {
        emit writeLog("MCP门控参数设置成功", 0, true);
    }
    else
    {
        emit writeLog("MCP门控参数设置失败", 2, false);
    }
    ui->mcp_controller_edit_widget->setEnabled(ui->chk_gateMode_mcp->isChecked() && !ui->chk_gateMode_external->isChecked());
    emit syncParameters();
}

// MCP外部触发变更槽函数
void SKFunctionSet::onMCPGateCancelClicked()
{
    setMCPGateMode(m_device->getParameter("MCPGatingMode").value<uint8_t>());
    setMCPDelay(m_device->getParameter("MCPGatingDelayNs").value<int>());
    setMCPPulseWidth(m_device->getParameter("MCPGatingPulseWidthNs").value<int>());
}

// 启动监控槽函数
void SKFunctionSet::onMonitorEnabledChanged(bool enabled)
{
    // 设置到设备
    if (enabled) {
        CommandResult result = m_device->setMonitorSignalQuery();
        if (CommandResult::Success == result)
        {
            m_IsMonitor=true;
            m_MonitorTimer.start();
            emit writeLog(QString("启动监控%1成功").arg(enabled ? "开启" : "关闭"), 0, true);
        }
        else
        {
            emit writeLog(QString("启动监控%1失败").arg(enabled ? "开启" : "关闭"), 2, false);
            // 恢复之前的状态
            bool monitorEnabled = m_device->getParameter("MonitorEnabled").toBool();
            ui->chk_monitor_enable->setChecked(monitorEnabled);
        }
    }
    else
    {
        if(m_IsMonitor)
        m_MonitorTimer.stop();
    }
}

//更新监控信息
void SKFunctionSet::onUpdateMonitorInfo()
{
    if(!m_IsMonitor)
    {
        return;
    }
    
    if(m_device)
    {
        // 获取AD值并更新表格
        QVector<uint16_t> adValues = m_device->getParameter("ADValue").value<QVector<uint16_t>>();
        for(int i = 0; i < adValues.size() && i < 8; ++i)
        {
            // 将AD值转换为电压值
            double voltage = adValues[i] / 1000.0;
            QTableWidgetItem *item = new QTableWidgetItem(QString("%1").arg(voltage, 0, 'f', 3));
            item->setTextAlignment(Qt::AlignCenter);
            ui->tableWidget->setItem(i, 0, item);
        }
        
        // 获取GPIO状态并更新表格
        QVector<bool> gpioStatus = m_device->getParameter("GPIOStatus").value<QVector<bool>>();
        for(int i = 0; i < gpioStatus.size() && i < 8; ++i)
        {
            QString status = gpioStatus[i] ? "高" : "低";
            QTableWidgetItem *item = new QTableWidgetItem(status);
            item->setTextAlignment(Qt::AlignCenter);
            ui->tableWidget->setItem(i, 1, item);
        }
    }
}

void SKFunctionSet::onSyncParameters()
{
    fetchParametersFromDevice();
}

// 触发延迟设置按钮槽函数
void SKFunctionSet::onTriggerDelaySetClicked()
{
    // 实现触发延迟设置按钮的槽函数
    uint32_t delay=getTriggerDelay();
    uint32_t pulseWidth=getTriggerPulseWidth();
    CommandResult result = m_device->setInternalTriggerDelay(delay,pulseWidth);
    if (CommandResult::Success == result)
    {
        emit writeLog(QString("内触发延迟设置成功"), 0, true);
    }
    else
    {
        emit writeLog(QString("内触发延迟设置失败"), 2, false);
        // 恢复之前的状态
        bool monitorEnabled = m_device->getParameter("MonitorEnabled").toBool();
        ui->chk_monitor_enable->setChecked(monitorEnabled);
    }
}

void SKFunctionSet::onTriggerDelayCancelClicked()
{
    // 实现触发延迟取消按钮的槽函数
    if (!m_device) return;
    
    // 从设备获取当前延迟值并更新UI
    setTriggerDelay(m_device->getParameter("TriggerDelayValue").toUInt());
    setTriggerPulseWidth(m_device->getParameter("TriggerDelayPulseWidthValue").toUInt());
}

void SKFunctionSet::onCathodeGatingModeToggled(bool checked)
{
    ui->mcp_controller_edit_widget->setEnabled(checked);
    if(!checked){
        ui->chk_gateMode_external->setChecked(checked);
    }
}

void SKFunctionSet::onExternalGatingModeToggled(bool checked)
{
    if(ui->chk_gateMode_mcp->isChecked()){
        ui->mcp_controller_edit_widget->setEnabled(!checked);
    }else{
        ui->chk_gateMode_external->setChecked(false);
    }
}

void SKFunctionSet::onCathodeGatingToggled(bool checked)
{
    ui->gate_edit_widget->setEnabled(checked);
    if(!checked){
        ui->chk_gate_external->setChecked(checked);
    }
}

void SKFunctionSet::onExternalGatingToggled(bool checked)
{
    if(ui->chk_gate_cathode->isChecked()){
        ui->gate_edit_widget->setEnabled(!checked);
    }else{
        ui->chk_gate_external->setChecked(false);
    }
}

void SKFunctionSet::onCloseButtonClicked()
{
    this->close();
}

// 鼠标事件处理
void SKFunctionSet::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        m_mousePressed = true;
        m_lastMousePosition = event->globalPos() - this->frameGeometry().topLeft();
        event->accept();
    }
}

void SKFunctionSet::mouseMoveEvent(QMouseEvent *event)
{
    if (m_mousePressed && (event->buttons() & Qt::LeftButton)) {
        m_dragging = true;
        this->move(event->globalPos() - m_lastMousePosition);
        event->accept();
    }
}

void SKFunctionSet::mouseReleaseEvent(QMouseEvent *event)
{
    m_mousePressed = false;
    m_dragging = false;
    event->accept();
}
